首页 > 试题广场 >

数组中的最长连续子序列

[编程题]数组中的最长连续子序列
  • 热度指数:36175 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定无序数组arr,返回其中最长的连续序列的长度(要求值连续,位置可以不连续,例如 3,4,5,6为连续的自然数)

数据范围: ,数组中的值满足
要求:空间复杂度 ,时间复杂度
示例1

输入

[100,4,200,1,3,2]

输出

4
示例2

输入

[1,1,1]

输出

1

备注:

function MLS( arr ) {
    // write code here
    const newArr = [...new Set(arr)].sort((a, b) => a - b)
    let max = 0
    let point = -1
    let pre = Infinity
    newArr.forEach((item, index) => {
        if (point === -1) {
            max = 1
            point = 0
        } else {
            if (item === pre + 1) {
                max = Math.max(max, index - point + 1)
            } else {
                point = index
            }
        }
        pre = item
    })
    return max
}

发表于 2021-11-19 16:39:03 回复(0)

问题信息

难度:
1条回答 5780浏览

热门推荐

通过挑战的用户

查看代码